package com.hmall.gateway.filters;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断主否需要做登录拦截
        String url = request.getPath().toString();
        if(isExclude(url)){
            //放行不需要拦截得请求
            return chain.filter(exchange);
        }
        //3.获取token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");
        //当headers不为null和空时，获取token
//        if(headers != null || !headers.isEmpty()){
//            token=headers.get(0);
//        }
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        //4.校验并解析token
        Long userId =null;
        try {
            userId =jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            //拦截，设置状态码401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完结，后面的过滤器就不会执行，也不会请求转发了
            return response.setComplete();
        }
        //  5.传递用户信息--》将用户信息保存到请求头
        System.out.println("userId="+userId);
        String uId = userId.toString();
        ServerWebExchange build = exchange.mutate().request(builder -> builder.header("user-info", uId))
                .build();
        // 6.放行
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    public boolean isExclude(String url){
        for (String pathPattern:authProperties.getExcludePaths()){
            if(antPathMatcher.match(pathPattern,url)){
                return true;
            }
        }
        return false;
    }
}
